/**
 * @param {character[]} tasks
 * @param {number} n
 * @return {number}
 */
var leastInterval = function (tasks, n) {
  //定义一个数组frequency：存储每个字母的出现频率
  const frequency = new Array(26).fill(0)
  //统计字符的出现频率，存入数组frequency并升序排序
  for (let task of tasks) {
    let index = task.charCodeAt(0) - 'A'.charCodeAt(0)
    frequency[index]++
  }
  frequency.sort((a, b) => a - b)
  //统计最高频率 最高频率的出现次数
  let maxFrequency = frequency[25]
  let maxFrequencyCount = 1
  for (let i = 24; i >= 0; i--) {
    if (frequency[i] === maxFrequency) {
      maxFrequencyCount++
    } else {
      break
    }
  }
  //返回最短冷却时间：防止极端情况，需要公示结果和任务长度取较大值
  return Math.max((maxFrequency - 1) * (n + 1) + maxFrequencyCount, tasks.length)
};

leastInterval(["A", "A", "A", "B", "B", "B"], 2)